<?php

namespace App\Models\Goods;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;

/**
 * 货品属性模型类
 *
 * @package App\Models
 * @author WangBin
 * @date 2021-06/11
 */
class Attributes extends BaseModel
{
    protected $table = 'b2c_goods_attributes';
    protected $primaryKey = 'attribute_id';

    /**
     * 获取属性列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(array $filter = [])
    {
        $attribute = Attributes::query();
        if(!empty($filter['name'])) {
            $attribute->where('name', 'like', '%' . $filter['name'] . '%');
        }
        if(!empty($filter['attr_bn'])) {
            $attribute->where('attr_bn', 'like', '%' . $filter['attr_bn'] . '%');
        }
        if(isset($filter['is_active'])) {
            $attribute->where('is_active', $filter['is_active']);
        }
        $attribute->orderByDesc('created_at');
        return $attribute;
    }

    /**
     * 根据ID获取属性
     *
     * @param int $specId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $specId)
    {
        return Attributes::query()->where('attribute_id', $specId)->first();
    }

    /**
     * 保存属性
     *
     * @param array $data
     * @return mixed
     */
    public static function saveData(array $data)
    {
        $attribute = new Attributes();
        if($data['attribute_id']) {
            $attribute = Attributes::find($data['attribute_id']);
        }
        unset($data['attribute_id']);
        foreach ($data as $field => $value)
        {
            $attribute->{$field} = $value;
        }
        $attribute->save();
        return $attribute->attribute_id;
    }

    /**
     * 检查字段值唯一性
     *
     * @param string $field
     * @param string $value
     * @param int $id
     * @return bool
     */
    public static function checkUnique(string $field, string $value, int $id = 0)
    {
        $attribute = Attributes::query();
        if($id) {
            $attribute->where('attribute_id', '!=', $id);
        }
        return $attribute->where($field, $value)->exists();
    }

    /**
     * 批量删除属性
     *
     * @param array $ids
     * @return mixed
     */
    public static function remove(array $ids)
    {
        return Attributes::query()->whereIn('attribute_id', $ids)->delete();
    }

    /**
     * 停用/启用属性
     *
     * @param int $attrId
     * @param int $isActive
     * @return int
     */
    public static function enable(int $attrId, int $isActive = 1)
    {
        return Attributes::query()->where('attribute_id', $attrId)->update(['is_active' => $isActive]);
    }
}